package com.flyox.game.fivetiger.test;

import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;
import java.net.UnknownHostException;

import com.flyox.game.fivetiger.tools.SubnetAddress;

public class IPServer {

	private boolean living=true;
	
	public IPServer() {
		int port;
		InetAddress group;
		MulticastSocket socket;
		try {
			SubnetAddress sa = new SubnetAddress();
			String s = sa.calculate();
			port = 5000; // 设置组播组的监听端口为5000
			group = InetAddress.getByName(s); // 设置组播组的地址为239.0.0.0
			socket = new MulticastSocket(port); // 初始化MulticastSocket类并将端口号与之关联
			socket.setSoTimeout(1000); // 设置组播数据报的发送范围为本地网络
			socket.setTimeToLive(1); // 设置套接字的接收数据报的最长时间
			socket.joinGroup(group); // 加入组播组
			String outMessage=getIpAddress();
			byte[] data=outMessage.getBytes();
			DatagramPacket packet;
			while (isLiving()) {
				packet = new DatagramPacket(data, data.length, group, port); // 创建一个DatagramPacket实例
				socket.receive(packet); // 向组播组发送当前时间
				packet.getData();
				Thread.sleep(1000);
			}
		} catch (Exception e) {
			System.out.println("Error: " + e); // 捕捉异常情况
		}
	}

	public boolean isLiving() {
		return living;
	}

	public void setLiving(boolean living) {
		this.living = living;
	}
	
	/**
	 * 获取本机IP
	 * 
	 * @return
	 */
	private String getIpAddress() {
		String result = null;
		InetAddress inet;
		try {
			inet = InetAddress.getLocalHost();
			result = inet.getHostAddress();
		} catch (UnknownHostException e) {
			e.printStackTrace();
		}
		return result;
	}
}
